package com.itheima.service.impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.exception.BaseException;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMobileMapper;
import com.itheima.mapper.OrederSettingMobileMapper;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMobileMapper orderMobileMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrederSettingMobileMapper orederSettingMobileMapper;

    /**
     * 根据id查询预约信息
     * @param id
     * @return
     */
    public OrderVo getById(Integer id) {
        OrderVo orderVo = orderMobileMapper.getById(id);
        return orderVo;
    }

    /**
     * 用户预约接口
     * @param orderDTO
     */
    public void add(OrderDTO orderDTO) {
        Integer id = memberMapper.getByName(orderDTO.getName());
        if (id == null) {
            Member member = new Member();
            BeanUtils.copyProperties(orderDTO,member);
            member.setPhoneNumber(orderDTO.getTelephone());
            memberMapper.insert(member);
        }
        if (!orderDTO.getValidateCode().equals(redisTemplate.opsForValue().get(orderDTO.getTelephone()))) {
            throw new BaseException(MessageConstant.VALIDATECODE_ERROR);
        }
        OrderSetting orderSetting = orederSettingMobileMapper.getByDate(orderDTO.getOrderDate());
        if (orderSetting.getNumber() == 0) {
            throw new BaseException(MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        if(orderSetting.getReservations() == orderSetting.getNumber()) {
            throw new BaseException(MessageConstant.ORDER_FULL);
        }
        List<Integer> setnealID = orderMobileMapper.getByMember(id);
        for (Integer setmeal : setnealID) {
            if (setmeal == orderDTO.getSetmealId()) {
                throw new BaseException(MessageConstant.HAS_ORDERED);
            }
        }
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orederSettingMobileMapper.update(orderSetting);

        orderMobileMapper.insert(orderDTO);
    }
}
